﻿using System.Collections.Generic;
using System.Linq;
using Apps.Web.Core;
using Apps.IBLL.RC;
using Apps.Locale;
using System.Web.Mvc;
using Apps.Common;
using Apps.IBLL;
using Apps.Models.RC;
using Microsoft.Practices.Unity;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Data;
using Apps.Models;
using Wantn.FIS.Enum;
using Apps.IBLL.PUB;
using Apps.Models.PUB;
using System.Text;
using System.Configuration;
using Apps.BLL.YANX;

namespace Apps.Web.Areas.RC.Controllers
{
    public class SAMPLINGController : BaseController
    {
        [Dependency]
        public IRC_SAMPLING_POINTBLL m_SAMPLING_POINTBLL { get; set; }
        [Dependency]
        public IRC_SAMPLING_IMAGEBLL m_SAMPLING_IMAGEBL { get; set; }
        [Dependency]
        public IRC_SAMPLINGBLL m_SAMPLINGBBL { get; set; }
        [Dependency]
        public Apps.IBLL.PUB.IPUB_SUPPLIERBLL m_PUB_SUPPLIERBLL { get; set; }
        [Dependency]
        public IPUB_TRANSPORTBLL m_TRANSPORTBLL { get; set; }
        [Dependency]
        public IPUB_MATERIELBLL m_MATERIELBLL { get; set; }
        [Dependency]
        public IPUB_MINEBLL m_MINEBLL { get; set; }
        ValidationErrors errors = new ValidationErrors();
        [SupportFilter]
        public ActionResult Index()
        {
            //var List = m_PUB_SUPPLIERBLL.GetList(ref GridPager.NotPage, "");
            //ViewBag.SUPPLIER_ID = new SelectList(List, "SUPPLIER_ID", "SUPPLIER_NAME");
            return View();
        }
        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetList(GridPager pager, string parentId)
        {
            List<RC_SAMPLING_POINTModel> list = m_SAMPLING_POINTBLL.GetListByParentId(ref GridPager.NotPage, "", parentId);
            GridRows<RC_SAMPLING_POINTModel> grs = new GridRows<RC_SAMPLING_POINTModel>();
            grs.rows = list;
            grs.total = pager.totalRows;
            return Json(grs);
        }

        #region 导出导入

        [HttpPost]
        [SupportFilter(ActionName = "Export")]
        public JsonResult CheckExportData(string LPR, string BATCH_CODE, string SAMPLING_STATUS, string SUPPLIER_ID, string SAMPLING_USER_NAME, string SAMPLING_BEGIN_TIME, string SAMPLING_END_TIME)
        {
            var whereLambda = PredicateBuilder.True<V_RC_SAMPLING>();

            if (!string.IsNullOrEmpty(LPR))
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.LPR.IndexOf(LPR) > -1);
            }
            if (!string.IsNullOrEmpty(BATCH_CODE))
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.BATCH_CODE.IndexOf(BATCH_CODE) > -1);
            }
            if (!string.IsNullOrEmpty(SAMPLING_STATUS) && SAMPLING_STATUS != "-1")
            {
                int status = Convert.ToInt32(SAMPLING_STATUS);
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_STATUS == status);

            }
            if (!string.IsNullOrEmpty(SUPPLIER_ID) && SUPPLIER_ID != "-1")
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SUPPLIER_ID == SUPPLIER_ID);
            }
            if (!string.IsNullOrEmpty(SAMPLING_USER_NAME))
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_USER_NAME.IndexOf(SAMPLING_USER_NAME) > -1);
            }
            if (!string.IsNullOrEmpty(SAMPLING_BEGIN_TIME))
            {
                DateTime STime = Convert.ToDateTime(SAMPLING_BEGIN_TIME);
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_BEGIN_TIME >= STime);
            }

            if (!string.IsNullOrEmpty(SAMPLING_END_TIME))
            {
                DateTime ETime = Convert.ToDateTime(SAMPLING_END_TIME).AddDays(1);
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_END_TIME <= ETime);
            }

            List<V_RC_SAMPLING> list = new BLL.RC.RCSAMPLINGBLL().GetPagerList(ref GridPager.NotPage, whereLambda);

            if (list.Count().Equals(0))
            {
                return Json(JsonHandler.CreateMessage(0, "没有可以导出的数据"));
            }
            else
            {
                return Json(JsonHandler.CreateMessage(1, "可以导出"));
            }
        }
        [SupportFilter]
        public ActionResult Export(string LPR, string BATCH_CODE, string SAMPLING_STATUS, string SUPPLIER_ID, string SAMPLING_USER_NAME, string SAMPLING_BEGIN_TIME, string SAMPLING_END_TIME)
        {
            var whereLambda = PredicateBuilder.True<V_RC_SAMPLING>();

            if (!string.IsNullOrEmpty(LPR))
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.LPR.IndexOf(LPR) > -1);
            }
            if (!string.IsNullOrEmpty(BATCH_CODE))
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.BATCH_CODE.IndexOf(BATCH_CODE) > -1);
            }
            if (!string.IsNullOrEmpty(SAMPLING_STATUS) && SAMPLING_STATUS != "-1")
            {
                int status = Convert.ToInt32(SAMPLING_STATUS);
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_STATUS == status);

            }
            if (!string.IsNullOrEmpty(SUPPLIER_ID) && SUPPLIER_ID != "-1")
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SUPPLIER_ID == SUPPLIER_ID);
            }
            if (!string.IsNullOrEmpty(SAMPLING_USER_NAME))
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_USER_NAME.IndexOf(SAMPLING_USER_NAME) > -1);
            }
            if (!string.IsNullOrEmpty(SAMPLING_BEGIN_TIME))
            {
                DateTime STime = Convert.ToDateTime(SAMPLING_BEGIN_TIME);
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_BEGIN_TIME >= STime);
            }

            if (!string.IsNullOrEmpty(SAMPLING_END_TIME))
            {
                DateTime ETime = Convert.ToDateTime(SAMPLING_END_TIME).AddDays(1);
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_END_TIME <= ETime);
            }

            List<V_RC_SAMPLING> list = new BLL.RC.RCSAMPLINGBLL().GetPagerList(ref GridPager.NotPage, whereLambda);

            JArray jObjects = new JArray();

            var hashSamplingType = EnumMvcHelper.GetEnumHash<SamplingType>();//采样方式
            var hashLayoutType = EnumMvcHelper.GetEnumHash<LayoutType>();//布点方式
            var hashSampleState = EnumMvcHelper.GetEnumHash<SamplingState>();//采样状态
            foreach (var item in list)
            {

                var jo = new JObject();
                jo.Add("批次号", item.BATCH_CODE);
                jo.Add("矿点名称", item.MINE_NAME);
                jo.Add("物料", item.MATERIEL_NAME);
                jo.Add("供应商", item.SUPPLIER_NAME);
                jo.Add("运输商", item.TRANSPORT_NAME);
                jo.Add("车牌号", item.LPR);
                jo.Add("采样机", item.SAMPLING_NODE_NAME);
                jo.Add("采样方式", item.SAMPLING_TYPE.HasValue ? hashSamplingType[item.SAMPLING_TYPE.Value] : "");
                jo.Add("布点方式", item.LAYOUT_TYPE.HasValue ? hashLayoutType[item.LAYOUT_TYPE.Value] : "");
                jo.Add("采样点数", item.SAMPLING_POINTS);
                jo.Add("采样桶号", item.SAMPLE_PAIL);
                jo.Add("样品重量（kg）", item.SAMPLE_WEIGHT);
                jo.Add("采样开始时间", (item.SAMPLING_BEGIN_TIME == null ? "" : Convert.ToDateTime(item.SAMPLING_BEGIN_TIME).ToString("yyyy-MM-dd HH:mm:ss")));
                jo.Add("采样结束时间", (item.SAMPLING_END_TIME == null ? "" : Convert.ToDateTime(item.SAMPLING_END_TIME).ToString("yyyy-MM-dd HH:mm:ss")));
                jo.Add("采样状态", item.SAMPLING_STATUS.HasValue ? hashSampleState[item.SAMPLING_STATUS.Value] : "");
                jo.Add("采样员", item.SAMPLING_USER_NAME);
                jo.Add("已交接", item.REVICED == true ? "是" : "否");
                jo.Add("已合样", item.BLENDED == true ? "是" : "否");
                jo.Add("已制样", item.MADE == true ? "是" : "否");

                ////批次号/煤种名称/供应商名称/车牌号/采样机名称/采样方式/布点方式/采用点数/采样桶号/样品重量(Kg)/采样开始时间/采样结束时间/采样状态/采样员
                //jo.Add("批次号", item.BATCH_CODE);
                //jo.Add("煤种名称", item.MATERIEL_NAME);
                //jo.Add("供应商名称", item.SUPPLIER_NAME);
                //jo.Add("车牌号", item.LPR);
                //jo.Add("采样机名称", item.SAMPLING_NODE_NAME);
                //jo.Add("采样方式", item.SAMPLING_TYPE.HasValue ? hashSamplingType[item.SAMPLING_TYPE.Value] : "");
                //jo.Add("布点方式", item.LAYOUT_TYPE.HasValue ? hashLayoutType[item.LAYOUT_TYPE.Value] : "");
                //jo.Add("采样点数", item.SAMPLING_POINTS);
                //jo.Add("采样桶号", item.SAMPLE_PAIL);
                //jo.Add("采样重量(Kg)", item.SAMPLE_WEIGHT);
                //jo.Add("采样开始时间", item.SAMPLING_BEGIN_TIME);
                //jo.Add("采样结束时间", item.SAMPLING_END_TIME);
                //jo.Add("采样状态", item.SAMPLING_STATUS.HasValue ? hashSampleState[item.SAMPLING_STATUS.Value] : "");
                //jo.Add("采样员", item.SAMPLING_USER_NAME);
                jObjects.Add(jo);
            }
            var dt = JsonConvert.DeserializeObject<DataTable>(jObjects.ToString());
            var exportFileName = string.Concat(
                "入厂采样信息",
                DateTime.Now.ToString("yyyyMMdd"),
                ".xlsx");
            return new ExportExcelResult
            {
                SheetName = "Sheet1",
                FileName = exportFileName,
                ExportData = dt
            };
        }
        #endregion

        [SupportFilter]
        public ActionResult BjError(string samplingId,string Ieguid="")
        {
            ViewBag.samplingId = samplingId;
            return View();
        }

        YANX_RECORD_BLL bll = new YANX_RECORD_BLL();
        [HttpPost]
        [SupportFilter]
        public JsonResult BjError(string samplingId, string examine,string Ieguid="")
        {
            try
            {
                if (string.IsNullOrEmpty(samplingId))
                    return Json(JsonHandler.CreateMessage(1, "参数错误"));
                if (string.IsNullOrEmpty(examine))
                    return Json(JsonHandler.CreateMessage(1, "参数错误"));
                bool error = examine == "有效" ? false : true;
                if (bll.ExamineError(samplingId, error))
                {
                    return Json(JsonHandler.CreateMessage(1, "操作成功"));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    return Json(JsonHandler.CreateMessage(0, "操作失败" + ErrorCol));
                }
            }
            catch
            {
                string ErrorCol = errors.Error;
                return Json(JsonHandler.CreateMessage(0, "审核失败" + ErrorCol));
            }
        }

        [SupportFilter]
        public ActionResult BuChong(string samplingId, string Ieguid = "")
        {
            ViewBag.samplingId = samplingId;
            return View();
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult BuChong(string samplingId, string rfid, string weight = "0",string isShouyang="")
        {
            try
            {
                if (string.IsNullOrEmpty(samplingId))
                    return Json(JsonHandler.CreateMessage(1, "参数错误"));
                if (string.IsNullOrEmpty(rfid))
                    return Json(JsonHandler.CreateMessage(1, "请输入桶卡号"));
                if (bll.BuChong(samplingId, rfid, weight, isShouyang))
                {
                    return Json(JsonHandler.CreateMessage(1, "操作成功"));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    return Json(JsonHandler.CreateMessage(0, "操作失败" + ErrorCol));
                }
            }
            catch
            {
                string ErrorCol = errors.Error;
                return Json(JsonHandler.CreateMessage(0, "审核失败" + ErrorCol));
            }
        }


        #region --主表查询--
        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetListParent(GridPager pager, string LPR, string BATCH_CODE, string SAMPLING_STATUS, string SUPPLIER_ID, string SAMPLING_USER_NAME, string SAMPLING_BEGIN_TIME, string SAMPLING_END_TIME, string PAIL, string MATERIEL_ID, string SAMPLING_NODE, string RFID = "")
        {

            var whereLambda = PredicateBuilder.True<V_RC_SAMPLING>();

            if (!string.IsNullOrEmpty(LPR))
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.LPR.IndexOf(LPR) > -1);
            }
            //if (!string.IsNullOrEmpty(RFID))
            //{
            //    whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.RFID.IndexOf(RFID) > -1);
            //}
            if (!string.IsNullOrEmpty(BATCH_CODE))
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.BATCH_CODE.IndexOf(BATCH_CODE) > -1);
            }
            if (!string.IsNullOrEmpty(SAMPLING_STATUS) && SAMPLING_STATUS != "-1")
            {
                int status = Convert.ToInt32(SAMPLING_STATUS);
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_STATUS == status);

            }
            if (!string.IsNullOrEmpty(SUPPLIER_ID) && SUPPLIER_ID != "-1")
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SUPPLIER_ID == SUPPLIER_ID);
            }
            if (!string.IsNullOrEmpty(SAMPLING_USER_NAME))
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_USER_NAME.IndexOf(SAMPLING_USER_NAME) > -1);
            }
            if (!string.IsNullOrEmpty(SAMPLING_BEGIN_TIME))
            {
                DateTime STime = Convert.ToDateTime(SAMPLING_BEGIN_TIME);
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_BEGIN_TIME >= STime);
            }

            if (!string.IsNullOrEmpty(SAMPLING_END_TIME))
            {
                DateTime ETime = Convert.ToDateTime(SAMPLING_END_TIME).AddDays(1);
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_END_TIME <= ETime);
            }
            if (!string.IsNullOrEmpty(MATERIEL_ID) && MATERIEL_ID != "-1")
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.MATERIEL_ID == MATERIEL_ID);
            }
            if (!string.IsNullOrEmpty(SAMPLING_NODE) && SAMPLING_NODE != "0")
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLING_NODE_NAME == SAMPLING_NODE);
            }
            if (!string.IsNullOrEmpty(PAIL))
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.SAMPLE_PAIL == int.Parse(PAIL));
            }
            if (!string.IsNullOrEmpty(RFID))
            {
                whereLambda = whereLambda.And<V_RC_SAMPLING>(m => m.RFID == RFID);
            }
            List<V_RC_SAMPLING> list = new BLL.RC.RCSAMPLINGBLL().GetPagerList(ref pager, whereLambda);

            GridRows<V_RC_SAMPLING> grs = new GridRows<V_RC_SAMPLING>();
            grs.rows = list;
            grs.total = pager.totalRows;
            return Json(grs);
        }
        #endregion

        #region 显示图片

        /// <summary>
        /// Action：获取图片文件
        /// </summary>
        public FileContentResult SamplingImg(string SAMPLING_ID, string ImgType)
        {
            setNoPagerAscById.sort = "SAMPLING_ID";
            var anModel = m_SAMPLING_IMAGEBL.GetById(SAMPLING_ID);
            //ushort bimg = ushort.Parse(anModel.BEFORE_IMAGE);
            //ushort aimg = ushort.Parse(anModel.AFTER_IMAGE);

            //byte[] dateArray = BitConverter.GetBytes(bimg);
            if (anModel != null)
            {
                if (ImgType == "1")
                {
                    return File(Convert.FromBase64String(anModel.BEFORE_IMAGE), "image/jpg", anModel.SAMPLING_ID.ToString());
                }
                else
                {
                    return File(Convert.FromBase64String(anModel.AFTER_IMAGE), "image/jpg", anModel.SAMPLING_ID.ToString());
                }
            }
            else
            {
                return null;
            }
        }

        #endregion


        [HttpPost]
        public JsonResult GetTranSuppList(string type)
        {
            List<SelectListItem> dataList = new List<SelectListItem>();
            if (int.Parse(type) == 0)
            {
                dataList.Add(new SelectListItem { Text = "=== 供应商 ===", Value = "-1" });
                List<PUB_SUPPLIERModel> list = m_PUB_SUPPLIERBLL.GetList(p => p.ENABLED);
                foreach (PUB_SUPPLIERModel model in list)
                {
                    dataList.Add(new SelectListItem { Text = model.SUPPLIER_NAME, Value = model.SUPPLIER_ID });
                }
            }
            else if (int.Parse(type) == 1)
            {
                dataList.Add(new SelectListItem { Text = "=== 运输商 ===", Value = "-1" });
                List<PUB_TRANSPORTModel> list = m_TRANSPORTBLL.GetList(ref GridPager.NotPage, "");
                foreach (PUB_TRANSPORTModel model in list)
                {
                    dataList.Add(new SelectListItem { Text = model.TRANSPORT_NAME, Value = model.TRANSPORT_ID });
                }
            }
            else if (int.Parse(type) == 2)
            {
                dataList.Add(new SelectListItem { Text = "=== 物料 ===", Value = "-1" });
                List<PUB_MATERIELModel> list = m_MATERIELBLL.GetList(a => true);
                foreach (PUB_MATERIELModel model in list)
                {
                    dataList.Add(new SelectListItem { Text = model.MATERIEL_NAME, Value = model.MATERIEL_ID });
                }
            }
            else if (int.Parse(type) == 3)
            {
                dataList.Add(new SelectListItem { Text = "=== 矿别 ===", Value = "-1" });
                List<PUB_MINEModel> list = m_MINEBLL.GetList(ref GridPager.NotPage, "");
                foreach (PUB_MINEModel model in list)
                {
                    dataList.Add(new SelectListItem { Text = model.MINE_NAME, Value = model.MINE_ID });
                }
            }
            else
            {
                //获取 煤炭类型下拉框
                dataList.Add(new SelectListItem { Text = "=== 类型 ===", Value = "" });

                try
                {
                    using (DBContainer db = new DBContainer())
                    {
                        string strConnDB = ConfigurationManager.ConnectionStrings["OracleDbContext"].ToString();
                        string sql = "select TYPE_STR from V_SELF_SAMPLING GROUP BY  TYPE_STR";
                        DataTable _dt = new DataTable();
                        Oracle.ManagedDataAccess.Client.OracleDataAdapter _orcDA = new Oracle.ManagedDataAccess.Client.OracleDataAdapter(sql, strConnDB);
                        _orcDA.Fill(_dt);

                        List<V_SELF_SAMPLING> list = ValueConvert.ToDataList<V_SELF_SAMPLING>(_dt);
                        foreach (V_SELF_SAMPLING model in list)
                        {
                            dataList.Add(new SelectListItem { Text = model.TYPE_STR, Value = model.TYPE_STR });
                        }
                    }
                }
                catch (Exception ex)
                {
                    return Json(JsonHandler.CreateMessage(1, Resource.CheckSucceed));
                }


            }
            return Json(dataList);
        }
    }
}
